/**
 * 热门招聘
 * @author  Jello
 * @create  2018/11/12 16:52
 * @version 1.0
 * @company 广东蓝聘科技网络有限公司
 **/
var curPage = 1;
var size = 12;
var userid_sign = "";
var workId = "";
var mechanismAddress = ""; //城市
var userToken = "";
var companyKey = "";
var login_status = "0";
var spinner = new Spinner(opts);

$(function() {
	userid_sign = sessionStorage.getItem("user_sign");
	userToken = sessionStorage.getItem("user_token") == null ? "" : sessionStorage.getItem("user_token");

	companyKey = sessionStorage.getItem("favorword") == undefined ? "" : sessionStorage.getItem("favorword");
	mechanismAddress = (sessionStorage.getItem("favorkey") == undefined || sessionStorage.getItem("favorkey") == "全国") ? "china" : sessionStorage.getItem("favorkey");
	$("#area").html(mechanismAddress == "china" ? "全国" : mechanismAddress);
	$("#companyKey").val(companyKey);

	//检测是否记住密码
	var loginSign = localStorage.getItem("phone_local");
	var pwdSign = localStorage.getItem("pwd_local");
	if(pwdSign) {
		$("#loginPhone").val(loginSign);
		$("#loginPwd").val($.base64.decode(pwdSign));
		$("#checkbox").attr("checked", true);
	} else {
		$("#loginPhone").val(loginSign);
		$("#loginPwd").val("");
		$("#checkbox").attr("checked", false);
	}

	if(userid_sign) {
		$("#nickname").html(sessionStorage.getItem("nickname"));
		$(".person_header").show();
		login_status = "1";
	} else {
		$(".header_right").show();
	}

	//菜单栏切换
	$(".info").click(function() {
		$(".tab_nav").toggle();
		$("#menubar").attr("src", $(".tab_nav").is(":hidden") ? "img/personal/arrow_bottom.png" : "img/personal/arrow_top.png");
	});

	//全部城市	
	$("#allcity_btn").click(function() {
		stopScroll();
		$(".citybox").show();
	})
	$("#close_btn").click(function() {
		$(document).unbind("scroll");
		$(".citybox").hide();
		$("#area").html("全国");
		queryHotWork();
	})

	//获取城市列表值
	$("#city_btn li").click(function() {
		var value = $(this).text();
		$("#area").html(value);
		if(value == "全国" || value == "全部城市") {
			mechanismAddress = "china";
			sessionStorage.setItem("favorkey", "全国");
		} else {
			mechanismAddress = value;
			sessionStorage.setItem("favorkey", mechanismAddress);
		}
		if(value != "全部城市") {
			companyKey = $("#companyKey").val();
			queryHotWork();
		}
	});

	//弹出层获取城市列表值
	$("#hotcity li").click(function() {
		var value = $(this).text();
		$("#area").html(value);
		if(value == "全国") {
			mechanismAddress = "china";
			sessionStorage.setItem("favorkey", "全国");
		} else {
			mechanismAddress = value;
			sessionStorage.setItem("favorkey", mechanismAddress);
		}
		//关闭弹出层
		$(document).unbind("scroll");
		$(".citybox").hide();
		//查询热门招聘
		companyKey = $("#companyKey").val();
		queryHotWork();
	})

	$(".ct-li").unbind('click').click(function() {
		var _index = $(this).index(); //获取点击元素的下标
		$(this).addClass("one") //给点击的元素添加类
			.siblings().removeClass(); //相邻元素隐藏类
		$(".item").eq(_index).show()
			.siblings().hide(); //选择item元素中第_index个显示出来，相邻元素被隐藏
	})

	//选择省份
	$("#province_btn li").click(function() {
		var city = $(this).text();
		$(".citybox").hide();
		$(".basebox").show();
		$("#curProvince").text(city)

		//遍历省的地级市 
		$.each(citydata, function(key, value) {
			if(key == city) {
				var cityList = value;
				$("#city_btn2").empty();
				var html_city = "";
				for(var i = 0; i < cityList.length; i++) {
					var city_html = '<li onclick="selectCity(\'' + cityList[i] + '\')">' + cityList[i] + '</li>'
					html_city += city_html
				}
				$("#city_btn2").append(html_city);
			}
		});
	})
	//弹出层全国
	$("#province_btn2 li").click(function() {
		var city = $(this).text();
		$("#curProvince").text(city);
		$(".ct-li").addClass("one");
		$(".item").eq(1).show().siblings().hide(); //选择item元素中第index个显示出来，相邻元素被隐藏
		$(".ct-ul li").eq(1).addClass("one").siblings().removeClass(); //给点击的元素添加类

		//遍历省的地级市 
		$.each(citydata, function(key, value) {
			if(key == city) {
				var cityList = value;
				$("#city_btn2").empty();
				var html_city = "";
				for(var i = 0; i < cityList.length; i++) {
					var city_html = '<li onclick="selectCity(\'' + cityList[i] + '\')">' + cityList[i] + '</li>'
					html_city += city_html
				}
				$("#city_btn2").append(html_city);
			}
		});
	})

	$("#close_btn2").click(function() {
		$(document).unbind("scroll");
		$(".basebox").hide();
		$("#area").html("全国");
	})

	//查询热门招聘
	flipOverPage(curPage);

	//根据关键字或企业查询
	$("#searchJob").click(function() {
		companyKey = $("#companyKey").val();
		sessionStorage.setItem("favorword", companyKey);
		queryHotWork();
	})
	$("#companyKey").keyup(function(event) {
		if(event.keyCode == 13) {
			companyKey = $("#companyKey").val();
			sessionStorage.setItem("favorword", companyKey);
			queryHotWork();
		}
	});

	//登录、注册弹出层
	$("#loginbtn").click(function() {
		stopScroll();
		$(".loginBox").show();
	})
	$("#registbtn").click(function() {
		stopScroll();
		$(".registBox").show();
	})
	//登录、注册遮罩层
	$(".logincover").click(function() {
		$(document).unbind("scroll");
		$(".loginBox").hide();
	})
	$(".registcover").click(function() {
		$(document).unbind("scroll");
		$(".registBox").hide();
	})

	//登录监听
	$("#loginPhone").on('input propertychange', function() {
		var phone = $(this).val();
		checkPhone(phone, "error2", "error1");
	})
	$("#loginPwd").on('input propertychange', function() {
		var pwd = $(this).val();
		checkPwd(pwd, "error2", "error1");
	})
	$("#loginPhone").click(function() {
		$(this).css("background", 'url(img/icon/phone.png) no-repeat 12px center');
	})
	$("#loginPwd").click(function() {
		$(this).css("background", 'url(img/icon/pwd.png) no-repeat 12px center');
	})
	$("#loginPhone").blur(function() {
		$("#error2").html("");
		$("#error1").hide();
		$(this).css("background", '');
	})
	$("#loginPwd").blur(function() {
		$("#error2").html("");
		$("#error1").hide();
		$(this).css("background", '');
	})
	//注册监听
	$("#registPhone").on('input propertychange', function() {
		var phone = $(this).val();
		checkPhone(phone, "error4", "error3");
	})
	$("#registPwd").on('input propertychange', function() {
		var pwd = $(this).val();
		checkPwd(pwd, "error4", "error3");
	})
	$("#registPhone").click(function() {
		$(this).css("background", 'url(img/icon/phone.png) no-repeat 12px center');
	})
	$("#registPwd").click(function() {
		$(this).css("background", 'url(img/icon/pwd.png) no-repeat 12px center');
	})
	$("#registPhone").blur(function() {
		$("#error4").html("");
		$("#error3").hide();
		$(this).css("background", '');
	})
	$("#registPwd").blur(function() {
		$("#error4").html("");
		$("#error3").hide();
		$(this).css("background", '');
	})
	//验证码监听
	$("#code").click(function() {
		$(this).css("background", 'url(img/icon/code.png) no-repeat 12px center');
	})
	$("#code").blur(function() {
		$("#error4").html("");
		$("#error3").hide();
		$(this).css("background", '');
	})

	//登录
	$("#loginbox_btn").click(function() {
		var phone = $("#loginPhone").val();
		var pwd = $("#loginPwd").val();
		if(checkPhone(phone, "error2", "error1") && checkPwd(pwd, "error2", "error1")) {
			//登录接口上送
			var param = {};
			param.phone = phone;
			param.pwd = pwd;
			login(param, function(resultObj) {
				if(resultObj.data.msg == "null") {
					$("#error2").html("用户不存在");
					$("#error1").show();
				} else if(resultObj.data.msg == "error") {
					$("#error2").html("用户名或密码错误");
					$("#error1").show();
				} else {
					rememberPwd(); //回调记住密码
					sessionStorage.setItem("user_token", resultObj.data.userToken); //存储token
					sessionStorage.setItem("user_sign", resultObj.data.id); //登录返回userid，去验证是否登录
					login_status = "1";
					//获取个人资料
					var param = {};
					param.token = resultObj.data.userToken;
					getUserMaterial(param, function(data) {
						sessionStorage.setItem("role", data.role);
						sessionStorage.setItem("nickname", data.user_name);
						window.location.reload();
					});
				}
			})
		}
	});

	//获取验证码
	$("#code_btn").click(function() {
		var phoneNum = $("#registPhone").val(); //手机号
		var pwd = $("#registPwd").val(); //密码

		var checkValue = (checkPhone(phoneNum, "error4", "error3") && checkPwd(pwd, "error4", "error3"));
		if(checkValue) {
			//获取验证码接口上送
			var param = {};
			param.phone = phoneNum;
			param.type = 0;
			gainCode(param, function(resultObj) {
				if(resultObj.code == 0) {
					token = resultObj.data; //获取验证码成功后返回的token
					//开启验证码定时器
					for(i = 1; i <= 60; i++) {
						if(i == 1) {
							window.setTimeout("countDown(" + i + ")");
						} else {
							window.setTimeout("countDown(" + i + ")", (i - 1) * 1000);
						}
					}
				} else {
					$("#error4").html(resultObj.msg);
					$("#error3").show();
					return;
				}
			});
		}
	})

	//注册
	$("#registbox_btn").click(function() {
		var phoneNum = $("#registPhone").val(); //手机号
		var pwd = $("#registPwd").val(); //密码
		var code = $("#code").val(); //验证码
		var flag = (checkPhone(phoneNum, "error4", "error3") && checkPwd(pwd, "error4", "error3") && checkCode(code));
		if(flag) {
			var checked = $("#registcheck").prop("checked"); //协议checkbox
			if(!checked) {
				$("#error4").html("请阅读并勾选协议");
				$(".errorMsg2").show();
				return;
			}
			//校验验证码接口上送
			var param = {};
			param.phone = phoneNum;
			param.type = 0;
			param.code = code;
			param.token = token;
			mateCode(param, function(mateObj) {
				if(mateObj.code == 0) {
					//注册接口上送
					var param = {};
					param.phone = phoneNum;
					param.pwd = pwd;
					regist(param, function() {
						$(".registBox").hide();
						$(".errorbox").show();
						$(".errorMsg2").hide();
						setTimeout(function() {
							$(".errorbox").hide();
							window.location.href = "regist.html";
						}, 800);
					})
				} else {
					$("#error4").html(mateObj.msg);
					$("#error3").show();
					return;
				}
			})
		}
	})

	//免费登录
	$("#free_login").click(function() {
		window.open("regist.html");
	})

	//免费注册
	$("#free_regist").click(function() {
		window.open("regist.html?type=1");
	})
	//客服中心
	$("#service_btn1").click(function() {
		window.open("tencent://message/?uin=1423335266&Site=lanpin123.com&Menu=yes");
	})
	$("#service_btn2").click(function() {
		window.open("tencent://message/?uin=2028048473&Site=lanpin123.com&Menu=yes");
	})
	$("#service_btn3").click(function() {
		window.open("tencent://message/?uin=3341118684&Site=lanpin123.com&Menu=yes");
	})

})

/**
 * 弹出层省级城市
 * @param {Object} city
 */
function selectCity(city) {
	$(".basebox").hide();
	$(document).unbind("scroll");
	mechanismAddress = city.replace("市", "");
	$("#area").html(mechanismAddress);
	companyKey = $("#companyKey").val();
	sessionStorage.setItem("favorkey", mechanismAddress);
	//查询热门招聘
	queryHotWork();
}

/**
 * 查询热门招聘-分页
 * @param {Object} curPage
 */
function flipOverPage(curPage) {
	//查询热门招聘
	$.ajax({
		type: "get",
		url: serverUrl + "/workapi/get_work_list_api?userToken=" + userToken + "&status=" + login_status + "&page=" + curPage + "&size=" + size + "&type=1" + "&sortType=1" + "&mechanismAddress=" + mechanismAddress + "&mechanismName=" + companyKey,
		cache: false,
		async: false,
		contentType: "application/json; charset=utf-8",
		timeout: asktime,
		dataType: "json",
		crossDomain: true,
		beforeSend: function() {
			$("#myspin").text("");
			var target = $("#myspin").get(0);
			spinner.spin(target);
		},
		success: function(data) {
			closeSpin(300);
			var resultObj = eval(data);
			console.log(JSON.stringify(resultObj))
			$(".favor_ul").empty();
			if(resultObj.code == 0 && resultObj.data.list.length != 0) {
				for(var i = 0; i < resultObj.data.list.length; i++) {
					var lendType = ""; //借支
					var workType = "";
					var money = "";
					var isApply = ""; //是否报名
					var keyList = "";
					var workList = resultObj.data.list;
					var temp = workList[i].status; //0 正在招工 1 已经招满
					var lend_type = workList[i].lendType;
					var post_type = workList[i].postType;
					var reStatus = "none";

					if(lend_type == 1) {
						lendType = "可借支";
						var showLend = "block";
					}
					if(post_type == 1) {
						workType = "小时工";
						money = workList[i].workMoney + '元/小时';
					} else if(post_type == 0) {
						workType = "正式工";
						money = workList[i].wageRange + '元/月';
					}
					if(temp == 1) {
						recruitStatus1 = "block";
						recruitStatus2 = "none";
					} else {
						recruitStatus1 = "none";
						recruitStatus2 = "block";
					}
					if(workList[i].isApply == 0 && workList[i].isApply != null) {
						isApply = "block";
					} else {
						isApply = "none";
					}

					if(workList[i].key == null) {
						keyList = "";
					} else {
						keyList = workList[i].key; //关键字
					}
					if(workList[i].reStatus == 1) {
						reStatus = "block";
					}

					var favor_html = '<li><div class="favorwork" onclick="queryWorkDetail(' + workList[i].id + ',' + lend_type + ')">' +
						'<img src="img/common/hot.png" class="hotimg" />' +
						'<div class="favor_div"><div class="favor_con1"><span class="title1" style="color: #FF5454;display: ' + recruitStatus1 + '">已招满</span>' +
						'<span class="title1" style="display: ' + recruitStatus2 + '">需' + workList[i].workTypeName + '' + workList[i].maxNumber + '人</span>' +
						'<span class="title2">' + money + '</span><div class="key" style="display:' + showLend + '">' + lendType + '</div>' +
						'<span class="title9">' + workType + '</span><span class="title4">已报名' + workList[i].applyNumber + '人</span></div>' +
						'<div class="favor_con2"><div class="favorimg"><img src="' + workList[i].mechanismUrl + '" class="favor_logo" /><span class="title3" style="display:' + isApply + '">已报名</span></div><div class="favor_txt">' +
						'<span class="title5">' + workList[i].mechanismName + '</span><span class="title6">' + keyList + '</span>' +
						'<div class="title7" style="display:' + reStatus + '"><span>返' + workList[i].reMoney + '</span></div><span class="title8">' + workList[i].mechanismScore + '分</span></div></div></div></div></li>';

					$(".favor_ul").append(favor_html);
				}

				if(resultObj.data.totalSize > 12) { //显示分页条数
					//分页插件
					$(".favor_page").show();
					$("#page").paging({
						pageNo: resultObj.data.pageNum,
						totalPage: resultObj.data.totalPages,
						totalSize: resultObj.data.totalSize,
						callback: function(num) {
							curPage = num;
							flipOverPage(curPage);
						}
					})
				} else {
					$(".favor_page").hide();
				}
			} else if(resultObj.code == 10002) {
				window.location.href = "login.html";
			} else { //没有热门招聘
				$(".hot_empty").show();
				$(".favor3_con").hide();
				$(".favor_page").hide();
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			closeSpin(300);
			return;
		}
	});
}

/**
 * 选择城市查询热门招聘
 */
function queryHotWork() {
	$.ajax({
		type: "get",
		url: serverUrl + "/workapi/get_work_list_api?userToken=" + userToken + "&status=" + login_status + "&size=" + size + "&type=1" + "&sortType=1" + "&mechanismAddress=" + mechanismAddress + "&mechanismName=" + companyKey,
		cache: false,
		async: false,
		contentType: "application/json; charset=utf-8",
		timeout: 15000,
		dataType: "json",
		crossDomain: true,
		beforeSend: function() {
			$("#myspin").text("");
			var target = $("#myspin").get(0);
			spinner.spin(target);
		},
		success: function(data) {
			closeSpin(300);
			var resultObj = eval(data);
			console.log(JSON.stringify(resultObj))
			
			$(".favor_ul").empty();
			if(resultObj.code == 0 && resultObj.data.list.length != 0) {
				for(var i = 0; i < resultObj.data.list.length; i++) {
					var lendType = ""; //借支
					var workType = "";
					var money = "";
					var isApply = ""; //是否报名
					var keyList = "";
					var workList = resultObj.data.list;
					var temp = workList[i].status; //0 正在招工 1 已经招满
					var lend_type = workList[i].lendType;
					var post_type = workList[i].postType;
					var reStatus = "none";

					if(lend_type == 1) {
						lendType = "可借支";
						var showLend = "block";
					}
					if(post_type == 1) {
						workType = "小时工";
						money = workList[i].workMoney + '元/小时';
					} else if(post_type == 0) {
						workType = "正式工";
						money = workList[i].wageRange + '元/月';
					}
					if(temp == 1) {
						recruitStatus1 = "block";
						recruitStatus2 = "none";
					} else {
						recruitStatus1 = "none";
						recruitStatus2 = "block";
					}
					if(workList[i].isApply == 0 && workList[i].isApply != null) {
						isApply = "block";
					} else {
						isApply = "none";
					}

					if(workList[i].key == null) {
						keyList = "";
					} else {
						keyList = workList[i].key; //关键字
					}
					if(workList[i].reStatus == 1) {
						reStatus = "block";
					}

					var favor_html = '<li><div class="favorwork" onclick="queryWorkDetail(' + workList[i].id + ',' + lend_type + ')">' +
						'<img src="img/common/hot.png" class="hotimg" />' +
						'<div class="favor_div"><div class="favor_con1"><span class="title1" style="color: #FF5454;display: ' + recruitStatus1 + '">已招满</span>' +
						'<span class="title1" style="display: ' + recruitStatus2 + '">需' + workList[i].workTypeName + '' + workList[i].maxNumber + '人</span>' +
						'<span class="title2">' + money + '</span><div class="key" style="display:' + showLend + '">' + lendType + '</div>' +
						'<span class="title9">' + workType + '</span><span class="title4">已报名' + workList[i].applyNumber + '人</span></div>' +
						'<div class="favor_con2"><div class="favorimg"><img src="' + workList[i].mechanismUrl + '" class="favor_logo" /><span class="title3" style="display:' + isApply + '">已报名</span></div><div class="favor_txt">' +
						'<span class="title5">' + workList[i].mechanismName + '</span><span class="title6">' + keyList + '</span>' +
						'<div class="title7" style="display:' + reStatus + '"><span>返' + workList[i].reMoney + '</span></div><span class="title8">' + workList[i].mechanismScore + '分</span></div></div></div></div></li>';

					$(".favor_ul").append(favor_html);
				}
				
				 

				$(".hot_empty").hide();
				$(".favor3_con").show();
				if(resultObj.data.totalSize > 12) { //显示分页条数
					//分页插件
					$(".favor_page").show();
					$("#page").paging({
						pageNo: resultObj.data.pageNum,
						totalPage: resultObj.data.totalPages,
						totalSize: resultObj.data.totalSize,
						callback: function(num) {
							flipOverPage(num);
						}
					})
				} else {
					$(".favor_page").hide();
				}
			} else if(resultObj.code == 10002) {
				window.location.href = "login.html";
			} else { //没有热门招聘
				$(".hot_empty").show();
				$(".favor3_con").hide();
				$(".favor_page").hide();
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			closeSpin(300);
			return;
		}
	});
}

/**
 * 查询招聘详情
 */
function queryWorkDetail(id, lend) {
	workId = id;
	sessionStorage.setItem("lendType", lend);
	window.location.href = "jobdetail.html?id=" + workId;
}

function indexPage() {
	sessionStorage.removeItem('favorword');
	sessionStorage.removeItem('favorkey');
	if(userid_sign) {
		window.location.href = "index.html";
	} else {
		window.location.href = "login.html";
	}
}

/**
 * 验证码倒计时
 * @param {Object} count 倒数
 */
function countDown(count) {
	if(count == 60) {
		$("#code_btn").html("获取验证码");
		$("#code_btn").attr('disabled', false);
	} else {
		left_time = 60 - count;
		$("#code_btn").attr('disabled', true);
		$("#code_btn").html(left_time + "秒重新发送");
	}
}

/**
 * 记住密码
 */
function rememberPwd() {
	var phoneNum = $("#loginPhone").val(); //手机号
	var pwd = $("#loginPwd").val(); //密码
	var checked = $('#checkbox').is(':checked');
	if(checked) { //选中记住密码,永久存储本地
		localStorage.setItem("phone_local", phoneNum);
		localStorage.setItem("pwd_local", $.base64.encode(pwd));
	} else {
		localStorage.removeItem("pwd_local");
	}
}

/**
 * 校验手机号
 */
function checkPhone(phone, showTxt, showId) {
	var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
	if(phone == "") {
		$("#" + showTxt).html("手机号码不能为空");
		$("#" + showId).show();
		return;
	} else if(!reg.test(phone)) {
		$("#" + showTxt).html("手机号码格式错误");
		$("#" + showId).show();
		return;
	} else {
		$("#" + showTxt).html("");
		$("#" + showId).hide();
	}
	return true;
}

/**
 * 校验密码
 * @param {Object} pwd
 */
function checkPwd(pwd, showTxt, showId) {
	if(pwd == "") {
		$("#" + showTxt).html("密码不能为空");
		$("#" + showId).show();
		return;
	} else if(pwd.indexOf(" ") >= 0) {
		$("#" + showTxt).html("密码中不能有空格字符");
		$("#" + showId).show();
		return;
	} else if((/[\u4e00-\u9fa5]+/).test(pwd)) {
		$("#" + showTxt).html("密码不能包含中文");
		$("#" + showId).show();
		return;
	} else if(pwd.length < 6 || pwd.length > 16) {
		$("#" + showTxt).html("密码长度为6-16位");
		$("#" + showId).show();
		return;
	} else {
		$("#" + showTxt).html("");
		$("#" + showId).hide();
	}
	return true;
}

/**
 * 检验验证码
 * @param {Object} code
 */
function checkCode(code) {
	var reg = /^[0-9]*$/;
	if(code == "") {
		$("#error4").html("验证码不能为空");
		$("#error3").show();
		return;
	} else if(!reg.test(code)) {
		$("#error4").html("验证码格式不正确");
		$("#error3").show();
		return;
	}
	return true;
}

/**
 * 跳转求职页面
 */
function applyPage() {
	sessionStorage.removeItem('favorword');
	sessionStorage.removeItem('favorkey');
	window.location.href = "applyjob.html";
}